package com.lanyou.esb.service;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanyou.cook.datadictionary.UserLogOpt;
import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.service.UserLogService;
import com.lanyou.esb.datadictionary.EnableType;
import com.lanyou.esb.entity.Http;
import com.lanyou.esb.exception.VisiblityException;
import com.lanyou.esb.repository.HttpRepository;

/**
 * 接口可见范围
 * 
 * @author Davey.wu
 */
@Service
public class VisiblityService {
	@Autowired
	private HttpRepository httpRepository;

	@Autowired
	private FieldSystemRepository fieldSystemRepository;

	@Autowired
	private UserLogService userLogService;

	/**
	 * 更新接口可访问列表
	 * 
	 * @param interfaceId
	 *            ：接口标识
	 * @param systems
	 *            ：系统集合
	 * @throws VisiblityException
	 */
	public void updateVisibleList(String interfaceId, List<String> systems)
			throws VisiblityException {
		Http http = httpRepository.findOne(Http.idSpecification(interfaceId));
		if (http == null) {
			throw new VisiblityException("找不到相应的接口！", 0);
		}
		if (!EnableType.ENABLE.ValueCode.equals(http.getIsEnable())) {
			throw new VisiblityException("接口不可用！", 0);
		}
		List<FieldSystem> fieldSystems = fieldSystemRepository.findAll(systems);
		if (fieldSystems == null || fieldSystems.isEmpty()) {
			http.getVisibleFieldSystems().clear();
		} else {
			http.getVisibleFieldSystems().clear();
			http.getVisibleFieldSystems().addAll(fieldSystems);
		}
		httpRepository.save(Arrays.asList(http));

		userLogService.save(UserLogOpt.MaintenanceChannelSystemManagement,
				null, String.format("更新接口“%s”可访问列表", http.getName()));
	}
}
